package org.dolirio.soft.hib.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class GenericHibernateDAO<T> extends HibernateDaoSupport {

	private Class<T> clazz;

	public void setClazz(Class<T> clazz) {

		this.clazz = clazz;
	}

	public Serializable save(T t) {

		return getHibernateTemplate().save(t);
	}

	public void update(T t) {
		getHibernateTemplate().update(t);
	}

	@SuppressWarnings("unchecked")
	public T retrieve(Serializable id) {

		return (T) getHibernateTemplate().get(clazz, id);
	}

	public void delete(T t) {

		getHibernateTemplate().delete(t);
	}

	@SuppressWarnings("unchecked")
	public List<T> getByAttribute(String attr, Serializable value) {

		Criteria criteria = getSession().createCriteria(clazz);

		if (value instanceof String) {

			criteria.add(Restrictions.like(attr, value));
		} else {

			criteria.add(Restrictions.eq(attr, value));
		}

		return criteria.list();
	}
}
